package Servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class Servlet1 extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        ServletInputStream inputStream = request.getInputStream();
//        byte[] buffer = new byte[1024000];
//        int read = inputStream.read(buffer);//创造一个缓冲区
//        System.out.println(new String(buffer,0,read));

//                 判断是否为多段数据
        if (ServletFileUpload.isMultipartContent(request)){
//                创建FileItemFactory的实现类
            FileItemFactory fileItemFactory=new DiskFileItemFactory();
//                创建解析工具类ServletFileUpload；
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
//                进行解析，得到每一个表单项FileItem；
                List<FileItem>list = servletFileUpload.parseRequest(request);

                for (FileItem fileItem : list) {
                    if (fileItem.isFormField()){
                        //普通表单项的上传
                        System.out.println(fileItem.getFieldName());//表单项里面的name值
                        System.out.println(fileItem.getString("UTF-8"));//Value值
                    }else{
                        //文件的上传
                        System.out.println(fileItem.getName());//文件名
                        System.out.println(fileItem.getFieldName());//表单项里面的name值
                        fileItem.write(new File("D:\\360Downloads"+fileItem.getName()));//将文件保存在磁盘上
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
